<?php

namespace App\Http\Controllers\backend;

use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Session;

class LoginController extends BaseController {
	
	protected $redirectTo = '/backend';
	
	public function __construct() {
		$this->middleware ('guest:admin', [
			'except' => 'logout'
		]);
	}
	
	public function login() {
		return View::make('backend.login');
	}
	
	public function attempt() {
		$input = Input::all();
		$validation = Validator::make($input, self::$rules, self::$msgs);
		if ($validation->passes()) {
			if(Auth::guard('admin')->attempt([
				'cellphone' => $input['cellphone'],
				'password' => $input['password']
			], true)) {
				$administrator = Auth::guard('admin')->user();
				if(!is_null($administrator)) {
					return redirect('/backend');
				}
				Auth::logout();
			}

			Session::flash('msg', '您输入的帐号或密码有误。');
		}
		return Redirect::back()
				->withInput()
				->withErrors($validation);
	}
	
	public function logout() {
		Auth::logout();
		return Redirect::to('/backend/');
	}
	
	// Validation
	public static $rules = array(
		'cellphone' => 'required',
		'password' => 'required',
	);
	
	public static $msgs = array(
		'cellphone.required' => '请填写您的手机号码。',
		'password.required' => '请填写您的密码。',
	);
	
}
